<template>
  <div class="create-post-page">
    <h4>{{ isEditPage ? '编辑文章' : '新建文章' }}</h4>
    <uploader :beforeUpload="uploadCheck" :editUploadedData="editUploadedData" @file-uploaded="fileUploaded" class="d-flex justify-content-center align-items-center bg-light my-4 text-secondary">
      <template #ready>
        <h2 class="my-0">点击上传头图</h2>
      </template>
      <template #uploading>
        <div class="spinner-border text-secondary" role="status">
          <span class="visually-hidden">Loading...</span>
        </div>
        <h2 class="my-0">正在上传</h2>
      </template>
      <template #uploaded="uploadProps">
        <img :src="uploadProps.uploadData.data.url" alt="">
      </template>
    </uploader>
    <validate-form @form-submit="onFormSubmit" class="w-100">
      <div class="mb-3">
        <label class="form-label">文章标题</label>
        <validate-input type="text" placeholder="请输入文章标题" :rules="titleRules" v-model="titleVal"></validate-input>
      </div>
      <div>
        <label class="form-label">文章标题</label>
        <validate-input
          rows="10"
          :tag="tag"
          placeholder="请输入文章内容"
          :rules="contentRules"
          v-model="contentVal"
        ></validate-input>
      </div>
      <template #submit>
        <button class="btn btn-primary">{{ isEditPage ? '更新文章' : '发表文章' }}</button>
      </template>
    </validate-form>
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue'
import ValidateForm from '../components/ValidateForm.vue'
import ValidateInput from '../components/ValidateInput.vue'
import uploader, { ResponseType } from '../components/Uploader.vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { beforeUploadCheck } from '../hooks/helper'
import createMessage from '../hooks/createMessage'
import { GlobalProps, ImageProps, PostProps } from '../store'

export default defineComponent({
  components: {
    ValidateForm,
    ValidateInput,
    uploader
  },
  setup () {
    const store = useStore<GlobalProps>()
    const router = useRouter()
    const route = useRoute()
    const titleRules = [{ type: 'require', message: '文章不能为空' }]
    const contentRules = [{ type: 'require', message: '文章不能为空' }]
    const tag = ref('textarea')
    const titleVal = ref()
    const contentVal = ref()
    const id = route.query.id
    const isEditPage = !!id
    const editUploadedData = ref()
    onMounted(() => {
      if (isEditPage) {
        store.dispatch('fetchPost', id).then((rawData:PostProps) => {
          editUploadedData.value = { data: rawData.image }
          titleVal.value = rawData.title
          contentVal.value = rawData.content
        })
      }
    })
    const uploadCheck = (file:File) => {
      const { passed, error } = beforeUploadCheck(file, {
        format: ['image/png', 'image/jpg', 'image/jpeg'],
        size: 1
      })
      if (error === 'format') {
        createMessage('上传的图片格式只支持png/jpg', 'error')
      }
      if (error === 'size') {
        createMessage('上传的图片不能大于 1MB ', 'error')
      }
      return passed
    }
    let imageId:string
    const fileUploaded = (rawData:ResponseType<ImageProps>) => {
      if (rawData.data._id) {
        imageId = rawData.data._id
      }
      createMessage('文件上传成功 图片ID' + rawData.data._id, 'success')
    }
    const fileUploadedError = () => {
      createMessage('文件上传失败', 'error')
    }
    const onFormSubmit = (res: boolean) => {
      if (res) {
        const { _id } = store.state.user
        const column = '5f4db92abb821789a5490ed3'
        if (column) {
          const newPost: PostProps = {
            title: titleVal.value,
            content: contentVal.value,
            column,
            author: _id,
            image: { url: imageId }
          }
          const actionName = isEditPage ? 'updatePost' : 'createPost'
          const sendData = isEditPage ? {
            id: route.query.id,
            payload: newPost
          } : newPost
          store.dispatch(actionName, sendData).catch((e) => {
            console.log(e)
          })
          router.push({ name: 'column', params: { id: column } })
        }
      }
    }
    return {
      titleRules,
      contentRules,
      titleVal,
      contentVal,
      tag,
      onFormSubmit,
      uploadCheck,
      fileUploaded,
      fileUploadedError,
      editUploadedData,
      isEditPage
    }
  }
})
</script>

<style>
.create-post-page .file-upload-container {
  height: 200px;
  cursor: pointer;
}
.create-post-page .file-upload-container img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
</style>
